#include "runcmd.h"

runcmd::runcmd(QObject *parent)
    : QObject(parent)
{
    m_process = new QProcess(this);
    // 设置工作目录
    m_process->setWorkingDirectory("/home/tf/physical_robot");

    // 配置环境变量
    setupEnvironment();
    setupConnections();
}

void runcmd::setupConnections()
{
    // 标准输出连接
    connect(m_process, &QProcess::readyReadStandardOutput, [this]() {
        emit outputReceived(QString::fromLocal8Bit(m_process->readAllStandardOutput()));
    });

    // 错误输出连接
    connect(m_process, &QProcess::readyReadStandardError, [this]() {
        emit errorReceived(QString::fromLocal8Bit(m_process->readAllStandardError()));
    });

    // 完成信号连接
    connect(m_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [this](int exitCode, QProcess::ExitStatus status) {
                m_childPid = -1;
                emit finished(exitCode);
            });

// 获取实际子进程PID（仅限Unix）
#ifdef Q_OS_UNIX
    connect(m_process, &QProcess::started, [this]() {
        m_childPid = m_process->processId();
        qDebug() << "Process started with PID:" << m_childPid;
    });
#endif
}

void runcmd::setupEnvironment()
{
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();

    // 添加ROS2环境变量（替换为实际路径）
    env.insert("ROS_DOMAIN_ID", "0");
    env.insert("AMENT_PREFIX_PATH", "/opt/ros/humble");
    env.insert("PYTHONPATH", "/opt/ros/humble/lib/python3.10/site-packages");
    env.insert("ROS_VERSION", "2");
    env.insert("ROS_PYTHON_VERSION", "3");

    // 设置PATH
    QString path = env.value("PATH");
    path.prepend("/opt/ros/humble/bin:");
    env.insert("PATH", path);

    m_process->setProcessEnvironment(env);
}

void runcmd::runProcess(QString str)
{
    if (m_process->state() == QProcess::Running) {
        emit errorReceived("已有进程在运行");
        return;
    }

    qDebug() << "Executing command:" << str;
    // 设置工作目录（绝对路径）
    m_process->setWorkingDirectory("/home/tf/physical_robot");

    // 构造完整命令链
    QString fullCommand = QString(
                              "source install/setup.sh && "  // 加载环境
                              "exec %2"         // 保持PID一致
                              ).arg(str);

    qDebug() << "Executing command:" << fullCommand;

    // 启动进程
    m_process->start("/bin/bash", QStringList() << "-c" << fullCommand);
    // // 使用exec替换shell进程保持PID一致
    // m_process->start("/bin/bash", QStringList() << "-c" << ("exec " + str));

    if (!m_process->waitForStarted(15000)) {
        emit errorReceived("进程启动超时");
    }
}

void runcmd::stopProcess()
{
    if (m_process->state() != QProcess::Running) return;

    qDebug() << "Stopping process...";

// Unix系统发送SIGINT
#ifdef Q_OS_UNIX
    if (m_childPid > 0) {
        ::kill(m_childPid, SIGINT);  // 优雅终止
    } else {
        m_process->terminate();      // 回退方案
    }
#else
    m_process->terminate();
#endif

    // 等待正常退出
    if (!m_process->waitForFinished(30000)) {
        qDebug() << "强制终止进程";
        m_process->kill();
    }
}

void runcmd::terminateProcess(bool forceKill)
{
    if (forceKill) {
        m_process->kill();
    } else {
        m_process->terminate();
    }
}
